package com.movie.ticket.sale.moviezuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.movie.ticket.sale.moviecommon.common.Result;
import com.netflix.zuul.context.RequestContext;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


/**
 * @author
 * @create 2020-11-20-12:19
 */
@Component
@Slf4j
public class ZullFileException extends SendErrorFilter {
    @Resource
    private ObjectMapper objectMapper;

    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    public int filterOrder() {
        return FilterConstants.SEND_ERROR_FILTER_ORDER - 1;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        boolean b = ctx.getThrowable() != null && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
        Throwable throwable = ctx.getThrowable();
        throwable.printStackTrace();
        log.info("是否拦截异常========={},异常：{}", b,throwable.getMessage());
        return b;
    }

    @SneakyThrows
    public Object run() {
        log.info("进入filter异常处理");
        try {
            RequestContext ctx = RequestContext.getCurrentContext();

            ExceptionHolder zuulException = findZuulException(ctx.getThrowable());

            log.info("调用出错{}",zuulException.getThrowable()+"没有值？");
//            异常转自定义格式
            Result fail = Result.fail( zuulException.getStatusCode(), zuulException.getErrorCause());
//        不再往后发送
            ctx.set(SEND_ERROR_FILTER_RAN, true);
            HttpServletResponse response=ctx.getResponse();
            response.getWriter().write(objectMapper.writeValueAsString(fail));
            response.setStatus(zuulException.getStatusCode());
            response.setContentType("application/json;charset=utf-8");
        } catch (Exception e) {
            ReflectionUtils.rethrowRuntimeException(e);
        }
        return "error";
    }
}
